package com.mf.service.impl.basic.webPage;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.emuns.enumsPublic.EnumPublicEnableOrDisable;
import com.mf.utils.UtilSql;
import com.mf.utils.tree.UtilTree;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.mf.entity.dto.basic.webPage.DtoWebMenu;
import com.mf.entity.req.basic.search.webPage.SearchReqWebMenu;
import com.mf.mapper.basic.webPage.MapperWebMenu;
import com.mf.service.basic.webPage.ServiceWebMenu;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Service
public class ImplServiceWebMenu extends ServiceImpl<MapperWebMenu, DtoWebMenu> implements ServiceWebMenu {

    /**
     * 参数查询条件
     */
    @Override
    public LambdaQueryWrapper<DtoWebMenu> fillParams(SearchReqWebMenu params) {
        LambdaQueryWrapper<DtoWebMenu> wrapper = loadQw();
        if (StringUtils.isNotBlank(params.getKey())) {
            wrapper.and(w -> {
                w.like(DtoWebMenu::getMetaTitle, params.getKey()).or().apply(UtilSql.sqlJsonKey(DtoWebMenu::getMetaRole), UtilSql.sqlJsonValue(params.getKey()));
            });
        }
        wrapper.eq(ObjectUtils.isNotEmpty(params.getStatus()), DtoWebMenu::getStatus, params.getStatus());
        return wrapper;
    }

    /**
     * 根据权限查询显示菜单
     */
    @Override
    public List<DtoWebMenu> listTreeByPermission(List<String> permissions) {
        SearchReqWebMenu params = new SearchReqWebMenu();
        params.setStatus(EnumPublicEnableOrDisable.ENABLE.getCode());
        List<DtoWebMenu> dtoWebMenus1 = findListByParams(params);

        Set<String> permissionSet = new HashSet<>(permissions);
        List<DtoWebMenu> dtoWebMenuList =
                dtoWebMenus1.stream().filter(dtoWebMenu -> permissionSet.containsAll(dtoWebMenu.getMetaRole())).toList();
        return UtilTree.buildTree(dtoWebMenuList);
    }

    /**
     * 根据id查询子节点数量
     */
    @Override
    public long countByPid(Integer id) {
        LambdaQueryWrapper<DtoWebMenu> wrapper = loadQw();
        wrapper.eq(DtoWebMenu::getPid, id);
        return count(wrapper);
    }
}